package array;

import java.util.Objects;

public class GameOfLife {
    public static void main(String[] args) {
        int[][] board = {{0,1,1},{0,0,1},{0,1,0},{0,0,0}};
        GameOfLife gameOfLife = new GameOfLife();
        for (int t = 0; t < 10; t++) {
            gameOfLife.gameOfLife(board);
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[i].length; j++) {
                    System.out.print(board[i][j] + " ");
                }
                System.out.println();
            }
            System.out.println("----------------------------");
        }

    }
    public void gameOfLife(int[][] board) {
        if (board == null || board.length == 0) {
            return;
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                int count = count(board,i,j);
                board[i][j] += (count * 10);
            }
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                int count = board[i][j] / 10;
                int val = board[i][j] % 10;
                if(count < 2){
                    board[i][j] = 0;
                } else if ((count == 2 || count == 3) && val == 1) {
                    board[i][j] = 1;
                } else if (count == 2 && val == 0) {
                    board[i][j] = 0;
                }else if (count == 3 && val == 0) {
                    board[i][j] = 1;
                } else if (count > 3) {
                    board[i][j] = 0;
                }
            }
        }
    }
    public int count(int[][] board,int i,int j) {
        int count = 0;
        int row = board.length;
        int col = board[0].length;
        int[][] neighbors = {{i-1,j-1},{i-1,j},{i-1,j+1},{i,j-1},{i,j+1},{i+1,j-1},{i+1,j},{i+1,j+1}};
        for (int m = 0; m < neighbors.length; m++) {
            int[] neighbor = neighbors[m];
            if(neighbor[0] < 0 || neighbor[1] < 0) continue;
            if(neighbor[0] >= row || neighbor[1] >= col) continue;
            int val = board[neighbor[0]][neighbor[1]] % 10;
            if(val == 1){
                count++;
            }
        }
        return count;
    }
}
